import numpy as np
import cv2 as cv
import glob

nw, nh = 7, 6

# termination criteria
criteria = (cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_MAX_ITER, 30, 0.001)
# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
objp = np.zeros((nh*nw, 3), np.float32)
objp[:, :2] = np.mgrid[0:nw, 0:nh].T.reshape(-1, 2)
# Arrays to store object points and image points from all the images.
objpoints = []  # 3d point in real world space
imgpoints = []  # 2d points in image plane.
images = glob.glob('Camera/*.jpg')
for fname in images:
    img = cv.imread(fname)
    img = cv.resize(img, (684, 912))
    gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    if 'IMG_20231017_145526' in fname or 'IMG_20231017_145600' in fname:
        gray = cv.threshold(gray, 160, 255, cv.THRESH_BINARY)[1]
    else:
        gray = cv.threshold(gray, 100, 255, cv.THRESH_BINARY)[1]

    # Find the chess board corners
    ret, corners = cv.findChessboardCorners(gray, (nw, nh), None)

    # If found, add object points, image points (after refining them)
    if ret == True:
        print(fname)
        # objpoints.append(objp)
        # corners2 = cv.cornerSubPix(gray, corners, (11, 11), (-1, -1), criteria)
        # imgpoints.append(corners2)
        # # Draw and display the corners
        # cv.drawChessboardCorners(img, (nw, nh), corners2, ret)

        for c in corners:
            center = np.array(c[0]).astype(np.int32)
            print(center)
            cv.circle(img, center, 2, (20, 200, 20), 2)

    cv.imshow('img', img)
    cv.waitKey(0)

cv.destroyAllWindows()
